<template>
	<div>
		<div class="breadcrumb">
			<el-breadcrumb separator="/">
				<el-breadcrumb-item>{{$store.state.company.companyName}}</el-breadcrumb-item>
				<el-breadcrumb-item>专家技术</el-breadcrumb-item>
				<el-breadcrumb-item>培训班</el-breadcrumb-item>
			</el-breadcrumb>
		</div>
		<div class="tableNavBox">
			<div class="menberConTitle flex" style="justify-content: space-between;">
				<div class="tableTitle">新增培训班</div>
				<!-- <div>
					<el-button type="primary" size="mini" class="topButton" round>置顶</el-button>
					<el-button type="primary" size="mini" class="topButton" round>新增</el-button>
				</div> -->
			</div>
			<div>
				<el-form :model="postData" class="demo-form-inline" label-width="100px">
					<el-form-item label="培训学校：">
						<el-input v-model="postData.trainingSchool" disabled class="formInput" placeholder="培训学校"></el-input>
					</el-form-item>
					<el-form-item label="主题：">
						<el-input v-model="postData.theme" class="formInput" placeholder="主题"></el-input>
					</el-form-item>
					<el-form-item label="关键词：">
						<el-input v-model="postData.keyWord" class="formInput" placeholder="关键词,以逗号分隔"></el-input>
					</el-form-item>
					<el-form-item label="培训时间：">
						<el-date-picker v-model="postData.dateList" type="daterange" class="formInputDatePicker" range-separator="-"
						 start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" @change="selectDate">
						</el-date-picker>
						共<span class="dayNub">{{mistiming}}</span>天
					</el-form-item>
					<el-form-item label="培训地点：">
						<el-input v-model="postData.address" class="formInput" placeholder="培训地点"></el-input>
					</el-form-item>
					<el-form-item label="培训对象：">
						<el-input v-model="postData.trainees" class="formInput" placeholder="培训对象"></el-input>
					</el-form-item>
					<el-form-item label="计划人数：">
						<el-input v-model="postData.planPeople" class="formInputNub" placeholder="计划人数"></el-input>人
					</el-form-item>
					<el-form-item label="培训专家：">
						<el-tag closable type="primary" size=" " class="expertTag" v-for="item in expertsListTag" :key="item.expertId" @close="closeTag(item.expertId)">{{item.expertName}}</el-tag>
						<el-button type="primary"  plain @click="addexpert">添加专家</el-button>
					</el-form-item>
					<el-row>
						<el-col :span="8">
							<el-form-item label="班主任：">
								<el-select v-model="postData.directorId" placeholder="班主任" @change="selectMenbers">
									<el-option v-for="item in menbersList" :label="item.name" :value="item.userId"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="联系电话：">
								<el-input v-model="postData.phone" disabled style="width: 193px;" placeholder="联系电话"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<el-form-item label="是否建群：">
						<el-radio-group v-model="postData.groupChat">
							<el-radio :label="1">是</el-radio>
							<el-radio :label="0">否</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="文件名称：">
						<div class="fileListName" v-for="(item, index) in fileListName" :key="index">
							{{ item }}
							<i class="el-icon-close fileListNameIcon" @click="deleteFiles(index)"></i>
						</div>
						<!-- <el-tag closable type="info" size=" " class="fileListName" effect="plain">
							<div class="fileListName">云阳县关于XXXX的技术培训</div>
						</el-tag> -->
						<el-upload class="upload-demo" action="https://jsonplaceholder.typicode.com/posts/" :http-request="uploadFiles"
						 :show-file-list="false">
							<el-button type="primary" :loading="uploadLoading" plain>上传附件</el-button>
						</el-upload>
					</el-form-item>
				</el-form>
			</div>
		</div>
		<div class="btnBox">
			<el-button type="primary" round @click="$router.back()">返回</el-button>
			<el-button type="primary" round @click="submitData">保存/修改</el-button>
			<!-- <el-button type="danger" round>删除</el-button> -->
		</div>
		<!-- 新增专家组 -->
		<el-dialog title="选择专家" :visible.sync="dialogVisible" width="800px">
			<el-table ref="multipleTable" :data="expertList.items" tooltip-effect="dark" style="width: 100%"  @select="rowSelect" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55"> </el-table-column>
				<el-table-column prop="expertName" label="姓名"></el-table-column>
				<el-table-column prop="phone" label="电话"></el-table-column>
				<el-table-column prop="educational" label="教育背景">
					<template slot-scope="scope">
						{{ scope.row.educational?scope.row.educational:'暂无' }}
					</template>
				</el-table-column>
				<el-table-column prop="fieldRelation" label="擅长领域">
					<template slot-scope="scope">
						{{ scope.row.fieldRelation?scope.row.fieldRelation:'暂无' }}
					</template>
				</el-table-column>
				<el-table-column prop="rankName" label="职级">
					<template slot-scope="scope">
						{{ scope.row.rankName?scope.row.rankName:'暂无' }}
					</template>
				</el-table-column>
			</el-table>
			<pagina-tion :totalNum="expertList.totalNum" @paginaClick="dialogTableDataPaginaClick"></pagina-tion>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="confirmAdd">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	export default {
		components: {

		},
		data() {
			return {
				companyId: '',
				companyName: this.$store.state.company.companyName,
				userId: '',
				mistiming: '0', // 所选时间的差值
				uploadLoading: false,
				postData: {
					companyId: '', // 公司ID
					trainingSchool: this.$store.state.company.companyName, // 公司名称---培训学校
					dateList: [], // 日期选择器的选择数据
					theme: '', // 培训主题
					keyWord: '', // 关键词
					startDate: '', // 开始时间
					endDate: '', // 结束时间
					address: '', // 培训地点
					trainees: '', // 培训对象
					planPeople: '', // 计划人数
					directorId: '', // 班主任用户ID
					phone: '', // 班主任电话
					groupChat: 0, // 是否创建群聊
					files: [], // 培训班附件HTTP路径集合
					experts: [] // 专家ID集合
				},
				expertsListTag: [],
				// 班主任列表
				menbersList: [],
				// 上传成功文件的名称列表
				fileListName: [],
				// 弹窗
				dialogVisible: false,
				expertList: '',
				dialogSelectData: new Map(),
				// 获取到的培训班数据
				// trainingData: ''
			}
		},
		created() {
			this.$store.commit('industrialis_leftNavIndex', 21)
		},
		mounted() {
			// this.$store.commit('set_teamNavIndex', 212)
			let store = this.$store.state.user
			this.userId = store.userInfo.id

			this.companyId = this.$store.state.company.selectCompanyId ?
				this.$store.state.company.selectCompanyId : this.$store.state.company.companyId

			this.getCompanyMenbers()
			
		},
		watch: {
			dialogVisible(newdata){
				if(newdata){
					// this.dialogSelectData.clear()
				}
			}

		},
		methods: {
			getClassDetail(){
				// 获取培训班详情
				this.$request.postForm(this.$api.getClassDetail, {
					classId: this.$route.query.id
				}).then( res => {
					if(res.code == 200){
						let data = res.data
						// this.trainingData = res.data
						this.postData.theme = data.theme
						this.postData.keyWord = data.keyWord
						
						this.postData.dateList.push(data.startDate)
						this.postData.dateList.push(data.endDate)
						this.postData.startDate = data.startDate
						this.postData.endDate = data.endDate
						// 计算有多少天
						let start_time = new Date(data.startDate).getTime()
						let end_time = new Date(data.endDate).getTime()
						this.mistiming = (end_time - start_time) / 1000 / 24 / 3600 + 1
						
						this.postData.address = data.address
						this.postData.trainees = data.trainees
						this.postData.planPeople = data.planPeople
						// 班主任
						this.postData.directorId = data.directorId
						this.menbersList.forEach((v)=>{
							if (v.userId === data.directorId) {
								this.postData.phone = v.phone
							}
						})
						// 专家
						if(data.trainingClassExpertResponses && data.trainingClassExpertResponses.length > 0){
							data.trainingClassExpertResponses.forEach((v)=>{
								this.postData.experts.push(v.id)
								let experts = {
									expertId: v.id,
									expertName: v.name
								}
								this.expertsListTag.push(experts)
								this.dialogSelectData.set(v.id, experts)
							})
						}
						// 文件
						if(data.enclosureEntities && data.enclosureEntities.length > 0){
							data.enclosureEntities.forEach((v)=>{
								this.fileListName.push(v.url.split('/')[v.url.split('/').length-1])
								this.postData.files = v.url
							})
						}
					}
				})
			},
			selectDate(e) {
				// 选择时间
				if (e && e.length > 0) {
					// 计算总共多少天
					let start_time = new Date(e[0]).getTime()
					let end_time = new Date(e[1]).getTime()
					this.mistiming = (end_time - start_time) / 1000 / 24 / 3600 + 1
					// 为开始和结束时间赋值
					this.postData.startDate = this.postData.dateList[0]
					this.postData.endDate = this.postData.dateList[1]
				}
			},
			submitData() {
				// 保存/修改
				
				if(!this.postData.theme){
					this.$message.error('请填写培训主题')
					return
				} else if(!this.postData.keyWord){
					this.$message.error('请填写关键词')
					return
				} else if(this.postData.dateList.length < 2){
					this.$message.error('请选择开始和结束时间')
					return
				} else if(!this.postData.address){
					this.$message.error('请填写培训地点')
					return
				} else if(!this.postData.trainees){
					this.$message.error('请填写培训对象')
					return
				} else if(!this.postData.planPeople){
					this.$message.error('请填写计划人数')
					return
				} else if(this.dialogSelectData.size < 1){
					this.$message.error('请选择专家')
					return
				} else if(!this.postData.directorId){
					this.$message.error('请选择班主任')
					return
				} else if(this.postData.files.length < 1){
					this.$message.error('请上传课件')
					return
				}
				this.postData.experts = []
				this.dialogSelectData.forEach((v,k)=>{
					this.postData.experts.push(v.expertId)
				})
				this.postData.experts.join(',')
				this.postData.companyId = this.companyId
				
				let postUrl = ''
				if(this.$route.query.id){
					// 修改
					postUrl = this.$api.updateClass
					this.postData.id = this.$route.query.id
				} else {
					// 新增
					postUrl = this.$api.trainingClassNewClass
				}
				this.$request.postForm(postUrl, this.postData).then(res=>{
					if(res.code == 200){
						this.$message.success('保存成功')
						this.$router.back()
					}
				})
				console.log(this.postData)
			},
			getCompanyMenbers() {
				// 获取公司成员 
				this.$request.postForm(this.$api.getUsersByCompanyId, {
					companyId: this.companyId,
					page: 1,
					pageSize: 20000
				}).then(res => {
					if (res.code == 200) {
						this.menbersList = res.data.items
						// 编辑获取数据
						if(this.$route.query.id){
							setTimeout(()=>{
								this.getClassDetail()
							},300)
						}
					}
				})
			},
			selectMenbers(e) {
				// 选择班主任、、赋值电话号码
				this.menbersList.filter(item => {
					if (item.userId === e) {
						this.postData.phone = item.phone
					}
				})
			},
			uploadFiles(file) {
				// 上传课件文件
				this.uploadLoading = true
				let formData = new FormData
				formData.append('file', file.file)
				formData.append('identifier', 'FILEPATH')
				this.$request.uploading(this.$api.uploadFilefileidentifier, formData).then(res => {
					if (res.code == 200) {
						this.postData.files.push(res.data)
						this.fileListName.push(file.file.name)
						this.$message.success('上传成功')
						this.uploadLoading = false
					} else {
						this.$message.success('失败成功,请重新上传')
						this.uploadLoading = false
					}
				}).catch(e => {
					this.$message.success('失败成功,请重新上传')
					this.uploadLoading = false
				})
			},
			deleteFiles(index) {
				// 删除上传的文件
				this.$confirm('确定要删除该文件吗?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.postData.files.splice(index, 1)
					this.fileListName.splice(index, 1)
					this.$message.success('删除成功')
				})
			},
			addexpert(page){
				// 获取专家列表
				this.dialogVisible = true
				this.$request.postForm(this.$api.queryExpertListNotInClass, {
					companyId: this.companyId,
					trainingClassId: '',
					page: page?page:1,
					pageSize: $globalData.pageSize
				}).then(res=>{
					if(res.code == 200){
						this.expertList = res.data
						setTimeout(() => {
							this.selectTables()
						}, 100)
					}
				})
			},
			closeTag(id){
				// 关闭tag标签
				if (this.dialogSelectData.has(id)) {
					this.dialogSelectData.delete(id)
					this.expertsListTag = []
					this.dialogSelectData.forEach((v,k)=>{
						this.expertsListTag.push(v)
					})
				}
				console.log()
			},
			// 弹窗
			dialogTableDataPaginaClick(val){
				this.addexpert(val)
			},
			confirmAdd(){
				// 确定添加专家
				// expertsListTag
				this.expertsListTag = []
				this.dialogSelectData.forEach((v,k)=>{
					this.expertsListTag.push(v)
				})
				this.dialogVisible = false
			},
			rowSelect(selection, row) {
				// 单选某一行时的函数
				if (this.dialogSelectData.has(row.expertId)) {
					this.dialogSelectData.delete(row.expertId)
				} else {
					this.dialogSelectData.set(row.expertId, row)
				}
			},
			handleSelectionChange(e) {
				// 表格选中数据
				e.forEach((v) => {
					this.dialogSelectData.set(v.expertId, v)
				})
			},
			selectTables() {
				// 初始化表格选中状态
				this.expertList.items.forEach((v, i) => {
					if (this.dialogSelectData.has(v.expertId)) {
						this.$refs.multipleTable.toggleRowSelection(v)
					}
				})
				this.$forceUpdate()
			},
		}
	}
</script>

<style scoped="scoped">
	.breadcrumb,
	.tableNavBox {
		padding: 20px;
	}

	.tableNavBox {
		padding-top: 0;
	}

	.tableTitle {
		font-size: 16px;
		font-family: Microsoft YaHei;
		font-weight: 400;
		color: #333333;
		line-height: 30px;
	}

	.menberConTitle {
		width: 100%;
		background: #F3F3F3;
		text-align: left;
		padding: 5px 20px;
		margin-bottom: 20px;
		/* margin-top: 20px; */
	}

	.topButton {
		width: 78px;
	}

	.dialogVisible>>>.el-input__inner {
		width: 270px;
	}

	.demo-form-inline {
		color: #5C5C5C;
	}

	.formInput {
		width: 500px;
	}

	.formInputNub {
		width: 100px;
		margin-right: 10px;
	}

	.formInputDatePicker {
		width: 440px;
		margin-right: 10px;
	}

	.fileListName {
		width: 500px;
		padding: 0 30px 0 10px;
		position: relative;
		border: 1px solid #DCDCDC;
		margin-bottom: 15px;
		align-items: center;
		color: #5C5C5C;
		border-radius: 5px;
	}

	.fileListNameIcon {
		position: absolute;
		right: 10px;
		cursor: pointer;
		top: 10px;
	}

	.fileListNameIcon:hover,
	.dayNub {
		color: #23B14D;
	}

	.dayNub {
		margin: 0 5px;
	}

	.btnBox {
		width: 100%;
		margin-top: 30px;
		padding: 30px 0;
		border-top: 1px solid #DCDCDC;
		text-align: center;
	}

	.btnBox button {
		width: 100px;
	}
	.expertTag{
		margin-right: 10px;
		margin-bottom: 10px;
	}
</style>
